package com.bianyuanren.pay.service.iospay.impl;

import com.alibaba.fastjson.JSONObject;
import com.bianyuanren.common.core.domain.AjaxResult;
import com.bianyuanren.common.exception.BusinessException;
import com.bianyuanren.common.utils.DateUtils;
import com.bianyuanren.framework.util.ShiroUtils;
import com.bianyuanren.pay.service.iospay.IosPayService;
import com.bianyuanren.pay.utils.IosVerifyUtil;
import com.bianyuanren.v4.mapper.member.PpMemberMapper;
import com.bianyuanren.v4.mapper.rechargerecord.PpRechargeRecordMapper;
import com.bianyuanren.v4.mapper.rechargespec.PpRechargeSpecMapper;
import com.bianyuanren.v4.pojo.balace.PpBalaceRecord;
import com.bianyuanren.v4.pojo.member.PpMember;
import com.bianyuanren.v4.pojo.member.PpMemberSpec;
import com.bianyuanren.v4.pojo.rechargerecord.PpRechargeRecord;
import com.bianyuanren.v4.pojo.rechargespec.PpRechargeSpec;
import com.bianyuanren.v4.pojo.viporder.PpVipOrder;
import com.bianyuanren.v4.service.balace.IPpBalaceRecordService;
import com.bianyuanren.v4.service.member.IPpMemberService;
import com.bianyuanren.v4.service.member.IPpMemberSpecService;
import com.bianyuanren.v4.service.rechargerecord.impl.PpRechargeRecordServiceImpl;
import com.bianyuanren.v4.service.viporder.IPpVipOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.bianyuanren.common.core.domain.AjaxResult.error;
import static com.bianyuanren.common.core.domain.AjaxResult.success;

/**
 * @author Administrator
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Slf4j
public class IosPayServiceImpl implements IosPayService {

    @Autowired
    private PpRechargeSpecMapper ppRechargeSpecMapper;

    @Autowired
    private PpRechargeRecordServiceImpl rechargeRecordService;

    @Autowired
    private PpRechargeRecordMapper ppRechargeRecordMapper;

    @Autowired
    private PpMemberMapper ppMemberMapper;

    @Autowired
    private IPpBalaceRecordService iPpBalaceRecordService;

    @Autowired
    private IPpVipOrderService ppVipOrderService;

    @Autowired
    private IPpMemberSpecService ppMemberSpecService;
    @Autowired
    private IPpMemberService ppMemberService;

    /**
     * ios 支付
     *
     * @param priceId       内部的充值规格id
     * @param transactionId 苹果内购交易ID
     * @param payload       苹果支付成功后返回的票据
     * @return ios充值钻石
     */
    @Override
    public AjaxResult iosPay(Long priceId, String transactionId, String payload) {
        //线上环境验证  0为沙河环境  1为线上环境
        String verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
        if (verifyResult == null) {
            throw new BusinessException("苹果验证失败，返回数据为空");
        }
        JSONObject appleReturn = JSONObject.parseObject(verifyResult);
        String states = appleReturn.getString("status");
        //无数据则沙箱环境验证
        if ("21007".equals(states)) {
            verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
            appleReturn = JSONObject.parseObject(verifyResult);
            states = appleReturn.getString("status");
        }
        // 前端所提供的收据是有效的    验证成功
        if (states.equals("0")) {
            String receipt = appleReturn.getString("receipt");
            JSONObject returnJson = JSONObject.parseObject(receipt);
            System.out.println("returnJson苹果弄内购砖石充值" + returnJson);
            //获取到苹果返回的json中的订单号
            String jsonTransactionId = returnJson.getString("transaction_id");
            //交易列表包含当前交易，则认为交易成功
            if (!jsonTransactionId.equals(transactionId)) {
                return error("当前交易不在交易列表中");
            }
            //处理业务逻辑
            Long appUserId = ShiroUtils.getAppUserId();
            //自动生成一个自己内部的订单号
            String orderSn = rechargeRecordService.getOrdersn();
            PpRechargeSpec ppRechargeSpec = new PpRechargeSpec();
            ppRechargeSpec.setId(priceId);
            PpRechargeSpec rechargeSpec = ppRechargeSpecMapper.selectPpRechargeSpecById(ppRechargeSpec.getId());
            //添加充值记录
            PpRechargeRecord ppRechargeRecord = new PpRechargeRecord();
            ppRechargeRecord.setOrderSn(orderSn);
            ppRechargeRecord.setUserId(appUserId);
            ppRechargeRecord.setPayType(3);
            ppRechargeRecord.setRechargeStatus(1);
            ppRechargeRecord.setRechargeMoney(rechargeSpec.getSpecMoney());
            ppRechargeRecord.setRechargeDiamond(rechargeSpec.getSpecVal());
            ppRechargeRecord.setRechargeTime(DateUtils.getNowDate());
            ppRechargeRecord.setRechargeType(0);
            ppRechargeRecordMapper.insertPpRechargeRecord(ppRechargeRecord);
            //修改余额
            PpMember ppMember = ppMemberMapper.selectPpMemberById(appUserId);
            ppMember.setBalance(ppMember.getBalance() + ppRechargeRecord.getRechargeDiamond());
            ppMemberMapper.updatePpMember(ppMember);
            //添加余额变动记录
            PpBalaceRecord balaceRecord = new PpBalaceRecord();
            balaceRecord.setOtherId(ppRechargeRecord.getId());
            balaceRecord.setUserId(appUserId);
            balaceRecord.setType(1);
            balaceRecord.setBalaceAlterationGold(rechargeSpec.getSpecVal().toString());
            balaceRecord.setBalaceAlterationTime(DateUtils.getNowDate());
            iPpBalaceRecordService.insertPpBalaceRecord(balaceRecord);
            return success("充值成功");
        } else {
            // return error("支付失败，错误码：" + states);
            return error("支付失败");
        }
    }

    /**
     * ios开通会员
     *
     * @param priceId
     * @param transactionId
     * @param payload
     * @return
     */
    @Override
    public AjaxResult vipiosPay(Long priceId, String transactionId, String payload) {
        //线上环境验证  0为沙河环境  1为线上环境
        String verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
        System.out.println("verifyResult+=====================================" + verifyResult);
        if (verifyResult == null) {
            throw new BusinessException("苹果验证失败，返回数据为空");
        }
        log.info("线上，苹果平台返回JSON:" + verifyResult);
        JSONObject appleReturn = JSONObject.parseObject(verifyResult);
        String states = appleReturn.getString("status");
        //无数据则沙箱环境验证
        if ("21007".equals(states)) {
            verifyResult = IosVerifyUtil.buyAppVerify(payload, 0);
            log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
            appleReturn = JSONObject.parseObject(verifyResult);
            states = appleReturn.getString("status");
        }
        log.info("苹果平台返回值：appleReturn" + appleReturn);
        // 前端所提供的收据是有效的    验证成功
        // 前端所提供的收据是有效的    验证成功
        if (states.equals("0")) {
            String receipt = appleReturn.getString("receipt");
            JSONObject returnJson = JSONObject.parseObject(receipt);
            System.out.println("returnJson苹果弄内购砖石充值" + returnJson);
            //获取到苹果返回的json中的订单号
            String jsonTransactionId = returnJson.getString("transaction_id");
            //交易列表包含当前交易，则认为交易成功
            if (!jsonTransactionId.equals(transactionId)) {
                return error("当前交易不在交易列表中");
            }
            //交易列表包含当前交易，则认为交易成功
            //处理业务逻辑
            Long appUserId = ShiroUtils.getAppUserId();
            //自动生成一个自己内部的订单号
            String orderSn = rechargeRecordService.getOrdersn();
            //查询会员规格
            PpMemberSpec rechargeSpec = ppMemberSpecService.selectPpMemberSpecById(priceId);
            //添加开通会员记录表
            PpVipOrder ppVipOrder = new PpVipOrder();
            ppVipOrder.setOrderNumber(orderSn);
            ppVipOrder.setMemberId(appUserId);
            ppVipOrder.setMemberSecond(rechargeSpec.getMemberSecond());
            ppVipOrder.setMemberSecondType(rechargeSpec.getMemberSecondType());
            ppVipOrder.setCurrentPrice(rechargeSpec.getCurrentPrice());
            ppVipOrder.setCreateTime(DateUtils.getNowDate());
            ppVipOrderService.insertPpVipOrder(ppVipOrder);
            //开通会员
            ppMemberService.dredgeMember(appUserId, Integer.valueOf(rechargeSpec.getMemberSecond()), rechargeSpec.getMemberSecondType(), orderSn);
            return success("开通会员成功");
        } else {
            // return error("支付失败，错误码：" + states);
            return error("支付失败");
        }
    }
}
